package com.hust.chatvedio.fragment;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.gson.Gson;
import com.makeramen.roundedimageview.RoundedImageView;
import com.hust.chatvedio.MainActivity;
import com.hust.chatvedio.R;
import com.hust.chatvedio.utils.Utils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

import static android.app.Activity.RESULT_OK;


public class PersonFragment extends Fragment implements View.OnClickListener {

    private RoundedImageView mUserAvatar;
    private ProgressDialog progressDialog;
    private TextView mUserName;
    private TextView mUserAccount;
    private Button mBtnUpdate;
    private Button mBtnCamera;
    private Uri mImageUri;
    private String ImgBase64;
    public static final int TAKE_PHOTO = 1;
    public static final int CHOOSE_PHOTO = 2;
    private static String url_updateAvatar = MainActivity.BaseURL + "updateUserAvatar";
    private static String url_getUserDetails = MainActivity.BaseURL + "getUserDetails";
    private int success;
    private String message;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_person, container, false);
        initView(view);
        try {
            initData(view);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return view;
    }


    private void initView(View view) {

        mUserAvatar = (RoundedImageView) view.findViewById(R.id.user_avatar);
        mUserName = (TextView) view.findViewById(R.id.user_name);
        mUserAccount = (TextView) view.findViewById(R.id.user_account);
        mBtnUpdate = (Button) view.findViewById(R.id.btn_update);
        mBtnUpdate.setOnClickListener(this);
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private void initData(View view) throws InterruptedException {
        getUserDetails(MainActivity.userName)
                .thenAccept(userAvatar -> {
                    // 在获取用户信息成功后加载头像
                    MainActivity.userAvatar = userAvatar;
                    Glide.with(view).load(MainActivity.userAvatar).into(mUserAvatar);
                    mUserName.setText(MainActivity.userName);
                    mUserAccount.setText("账号:" + MainActivity.userName);
                    // 关闭 ProgressDialog
                    progressDialog.dismiss();
                })
                .exceptionally(throwable -> {
                    // 处理异常情况
                    throwable.printStackTrace();
                    progressDialog.dismiss();
                    return null;
                });
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    public CompletableFuture<String> getUserDetails(String userName) {
        CompletableFuture<String> future = new CompletableFuture<>();
        RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
        String url = url_getUserDetails + "?userName=" + userName;
        Request request = new JsonObjectRequest(0, url, (String) null,
                jsonObject -> {
                    try {
                        //在进行异步任务前先显示一个 Progress Dialog
                        progressDialog = new ProgressDialog(getActivity());
                        progressDialog.setMessage("获取用户信息");
                        progressDialog.setIndeterminate(false);
                        progressDialog.setCancelable(true);
                        progressDialog.show();
                        success = jsonObject.getInt("success");
                        if (success == 1) {
                            success = jsonObject.getInt("success");
                            message = jsonObject.optString("message");
                            String userAvatar = jsonObject.optString("data");
                            future.complete(userAvatar); // 将结果传递给 CompletableFuture
                        }
                    } catch (JSONException e) {
                        future.completeExceptionally(e); // 将异常传递给 CompletableFuture
                    }
                }, volleyError -> {
            future.completeExceptionally(volleyError); // 将异常传递给 CompletableFuture
        });
        requestQueue.add(request);
        return future;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_update:
                //通过相册选择图片
                showBottomDialog();
                break;
        }
    }

    private void chooseFromAlbum() {
        if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, CHOOSE_PHOTO);
        } else {
            openAlbum();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case CHOOSE_PHOTO:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    openAlbum();
                } else {
                    Toast.makeText(getActivity(), "你已拒绝该权限的申请", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    private void openAlbum() {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent, CHOOSE_PHOTO);//打开相册
    }


    private void takePhoto() {
        //创建File对象，用于储存拍照后的图片
        File mOutPutImage = new File(getActivity().getExternalCacheDir(), "output_image.jpg");
        try {
            if (mOutPutImage.exists()) {
                mOutPutImage.delete();
            }
            mOutPutImage.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (Build.VERSION.SDK_INT >= 24) {
            //安卓版本大于7.0得到Uri的方式
            mImageUri = FileProvider.getUriForFile(getActivity(), "com.hust.chatvedio.fileProvider", mOutPutImage);
        } else {
            mImageUri = Uri.fromFile(mOutPutImage);
        }
        //启动相机服务
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
        startActivityForResult(intent, TAKE_PHOTO);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case TAKE_PHOTO:
                if (resultCode == RESULT_OK) {
                    try {
                        //将拍摄的照片显示出来,将拍摄到的照片解析成Bitmap对象
                        Bitmap bitmap = BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(mImageUri));
                        mUserAvatar.setImageBitmap(bitmap);
                        ImgBase64 = "data:image/jpg;base64," + Utils.bitmapToBase64(bitmap);
                        MainActivity.userAvatar = ImgBase64;
                        updateAvatar(ImgBase64);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case CHOOSE_PHOTO:
                if (resultCode == RESULT_OK) {
                    if (Build.VERSION.SDK_INT >= 19) {
                        //4.4及以上系统使用这个方法处理图片
                        //因 为 Android 系 统 从 4.4 版 本 开 始， 选 取 相 册 中 的 图 片 不 再 返 回 图 片 真 实 的 Uri 了，
                        // 而 是 一 个 封 装 过 的 Uri， 因 此 如 果 是 4.4 版 本 以 上 的 手 机 就 需 要 对 这 个 Uri 进 行 解 析 才 行。
                        handleImageOnKitKat(data);
                    } else {
                        handleImageBeforeKitKat(data);
                    }
                }
                break;
            default:
                break;
        }
    }

    private void handleImageBeforeKitKat(Intent data) {
//        data.getData()返回值有三种形式：content://，file://，/document/
//        content://可以intent.setAction(Intent.ACTION_VIEW)，intent.setData(uri)启动，uri.getPath()得到的是真实的路径，可以用ContentResolver从媒体库中取东西；
//        file://可以intent.setAction(Intent.ACTION_VIEW)，intent.setDataAndType(uri,type)启动，uri.getPath()得到的是真实的路径，不能从媒体库中取东西；
///       document/不能直接启动，也不能得到真实路径，要自己拼接。
        Uri uri = data.getData();
        String imagePath = getImagePath(uri, null);
        displayImage(imagePath);
    }

    @TargetApi(19)
    private void handleImageOnKitKat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(getActivity(), uri)) {
            //如果是document类型的Uri，则通过document id处理
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1];//解析出数字格式的id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if (" com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {    //equalsIgnoreCase忽略大小写来比较字符串值是否相等，getScheme（）返回当前链接使用的协议
            //如果是content类型的Uri，则使用普通方式处理
            imagePath = getImagePath(uri, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            //如果是file类型的Uri，则直接获取图片路径即可
            imagePath = uri.getPath();
        }
        //根据图片路径显示图片
        displayImage(imagePath);
    }

    private void displayImage(String imagePath) {
        if (imagePath != null) {
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            mUserAvatar.setImageBitmap(bitmap);
            ImgBase64 = "data:image/jpg;base64," + Utils.bitmapToBase64(bitmap);
            updateAvatar(ImgBase64);
            MainActivity.userAvatar = ImgBase64;
        } else {
            Toast.makeText(getActivity(), "无法打开图片", Toast.LENGTH_SHORT).show();
        }
    }

    private String getImagePath(Uri uri, String selection) {
        String path = null;
        //通过Uri和selection来获取真实的图片路径
        Cursor cursor = getActivity().getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToNext()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    public void updateAvatar(String base64) {
        RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
        Map<String, String> map = new HashMap<>();
        map.put("userName", MainActivity.userName);
        map.put("userAvatar", base64);
        //在进行异步任务前先显示一个 Progress Dialog
        progressDialog = new ProgressDialog(getActivity());
        progressDialog.setMessage("正在修改头像");
        progressDialog.setIndeterminate(false);
        progressDialog.setCancelable(true);
        progressDialog.show();
        Request request = new JsonObjectRequest(1, url_updateAvatar, new Gson().toJson(map),
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        try {
                            success = jsonObject.getInt("success");
                            message = jsonObject.optString("message");
                            if (success == 1) {
                                progressDialog.dismiss();
                                showDialog(getActivity(), message);
                            } else if (success == 0) {
                                progressDialog.dismiss();
                                showDialog(getActivity(), message);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
            }
        });
        requestQueue.add(request);
    }

    private void showDialog(Context context, String message) {
        MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(context);
        materialAlertDialogBuilder
                .setMessage(message)
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do
                    }
                });
        materialAlertDialogBuilder.show();
    }

    private void showBottomDialog() {
        //1、使用Dialog、设置style
        final Dialog dialog = new Dialog(getActivity(), R.style.DialogTheme);
        //2、设置布局
        View view = View.inflate(getActivity(), R.layout.dialog, null);
        dialog.setContentView(view);

        Window window = dialog.getWindow();
        //设置弹出位置
        window.setGravity(Gravity.BOTTOM);
        //设置弹出动画
        window.setWindowAnimations(R.style.main_menu_animStyle);
        //设置对话框大小
        window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();

        dialog.findViewById(R.id.tv_take_photo).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                takePhoto();
            }
        });

        dialog.findViewById(R.id.tv_take_pic).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                chooseFromAlbum();
            }
        });

        dialog.findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

    }


}